<template>
  <div class="pvz-container">
    <el-card v-if="gameState === 'setup'" class="setup-card" key="setup">
      <template #header><h1>知识挑战</h1></template>
      <el-form label-position="top">
        <el-form-item label="请输入挑战主题">
          <el-input v-model="topic" placeholder="例如：高等数学、唐代诗词、量子力学入门"></el-input>
        </el-form-item>
        <el-form-item label="选择难度">
          <el-radio-group v-model="difficulty">
            <el-radio-button label="简单" />
            <el-radio-button label="中等" />
            <el-radio-button label="困难" />
          </el-radio-group>
        </el-form-item>
        <el-button type="primary" size="large" @click="handleStartGame" :loading="isLoading" class="start-challenge-btn">开始挑战</el-button>
      </el-form>
    </el-card>

    <div v-if="gameState === 'playing'" class="playing-field" key="playing">
      <div class="game-hud">
        <div class="hud-item score-board">分数: {{ score }}</div>
        <div class="hud-item sun-board">☀️ 50</div>
        <div class="hud-item progress-board">题目: {{ currentQuestionIndex + 1 }} / {{ questions.length }}</div>
      </div>

      <div class="zombie-area">
        <transition name="zombie-transition">
          <div v-if="!isZombieDefeated" class="zombie" :key="currentQuestionIndex" :class="zombieClass">
            <svg viewBox="0 0 120 200" class="zombie-svg">
                <rect x="0" y="70" width="25" height="80" fill="#a3c18a" stroke="#6b8359" stroke-width="2" rx="10" transform="rotate(20 5 110)"/>
                <rect x="95" y="70" width="25" height="80" fill="#a3c18a" stroke="#6b8359" stroke-width="2" rx="10" transform="rotate(-20 115 110)"/>
                <rect x="10" y="60" width="100" height="110" fill="#bca88e" stroke="#8b4513" stroke-width="2" rx="10"/>
                <rect x="35" y="60" width="50" height="110" fill="#f0f0f0" />
                <path d="M 50 70 L 70 70 L 65 110 L 55 110 Z" fill="#606060"/>
                <circle cx="60" cy="50" r="40" fill="#a3c18a" stroke="#6b8359" stroke-width="2"/>
                <circle cx="45" cy="50" r="10" fill="white"><animate attributeName="r" values="10;1;10" dur="2s" repeatCount="indefinite" /></circle>
                <circle cx="45" cy="50" r="5" fill="black"/>
                <circle cx="75" cy="50" r="10" fill="white"/>
                <circle cx="75" cy="50" r="5" fill="black"/>
                <path d="M 40 70 Q 60 80 80 70" stroke="black" stroke-width="2" fill="none"/>
                <path d="M 20 0 L 100 0 L 90 45 L 30 45 Z" fill="#c0c0c0" stroke="#808080" stroke-width="2"/>
                <rect x="15" y="-5" width="90" height="10" fill="#a0a0a0" stroke="#808080" stroke-width="2" rx="5"/>
            </svg>
             <div class="question-bubble">
                <span class="question-text">{{ currentQuestion.question }}</span>
            </div>
          </div>
        </transition>
      </div>

      <div class="pea-container" ref="peaContainerRef"></div>

      <div class="plant-area">
        <div
          v-for="(option, key, index) in currentQuestion.options"
          :key="key"
          class="plant-card"
          :ref="el => plantRefs[index] = el"
          @click="!isSubmitting && handleAnswer(key, index)"
          :class="{ 'is-disabled': isSubmitting, 'is-correct': showFeedback && feedbackResult.correctAnswer === key, 'is-incorrect': showFeedback && selectedAnswer === key && !feedbackResult.isCorrect }"
          >
           <svg viewBox="0 0 100 100" class="plant-svg">
                <path d="M 20 95 C 30 70, 70 70, 80 95 Z" fill="#3c9b3a" />
                <rect x="42" y="60" width="16" height="35" fill="#59bd59" rx="8" />
                <circle cx="50" cy="45" r="35" fill="#59bd59" stroke="#3c9b3a" stroke-width="3"/>
                <rect x="75" y="32" width="25" height="25" fill="#59bd59" stroke="#3c9b3a" stroke-width="3" rx="12"/>
            </svg>
          <div class="option-text">{{ key }}. {{ option }}</div>
        </div>
      </div>
    </div>

    <el-card v-if="gameState === 'results'" class="results-card" key="results">
      <h1>挑战完成!</h1>
      <h2>你的最终得分是: {{ score }}</h2>
      <p>共答对 {{ score / 10 }} / {{ questions.length }} 题</p>
      <el-button @click="resetGame" class="start-challenge-btn">再来一局</el-button>
      <el-button @click="$router.push({ name: 'TeacherDashboard' })">返回工作台</el-button>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import quizGameService from '../../services/quizGameService';

const gameState = ref('setup');
const isLoading = ref(false);
const isSubmitting = ref(false);

const topic = ref('中国近代史');
const difficulty = ref('中等');

const sessionId = ref(null);
const questions = ref([]);
const currentQuestionIndex = ref(0);
const score = ref(0);

const peaContainerRef = ref(null);
const plantRefs = reactive([]);
const isZombieDefeated = ref(false);

const selectedAnswer = ref(null);
const feedbackResult = ref({});
const showFeedback = ref(false);

const currentQuestion = computed(() => questions.value[currentQuestionIndex.value] || {});
const zombieClass = computed(() => ({
    'hit': showFeedback.value && !feedbackResult.value.isCorrect,
}));


const handleStartGame = async () => {
  if (!topic.value) {
    ElMessage.warning('请输入挑战主题！');
    return;
  }
  isLoading.value = true;
  try {
    const data = await quizGameService.startGame(topic.value, difficulty.value);
    sessionId.value = data.sessionId;
    questions.value = data.questions;
    gameState.value = 'playing';
  } catch (error) {
    ElMessage.error(error.message);
  } finally {
    isLoading.value = false;
  }
};

const handleAnswer = async (answerKey, plantIndex) => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;
  selectedAnswer.value = answerKey;

  try {
    const result = await quizGameService.submitAnswer(sessionId.value, currentQuestionIndex.value, answerKey);
    score.value = result.score;
    feedbackResult.value = result;
    showFeedback.value = true;
    
    shootPea(plantIndex);
    
    setTimeout(() => {
      if (result.isCorrect) {
        isZombieDefeated.value = true;
      }
      
      setTimeout(() => {
        showFeedback.value = false;
        if (result.isGameOver) {
          gameState.value = 'results';
        } else if (currentQuestionIndex.value < questions.value.length -1) {
          currentQuestionIndex.value++;
          isZombieDefeated.value = false;
        } else {
           gameState.value = 'results';
        }
        isSubmitting.value = false;
        selectedAnswer.value = null;
      }, result.isCorrect ? 800 : 1000); 

    }, 500);

  } catch (error) {
    ElMessage.error(error.message);
    isSubmitting.value = false;
  }
};

const shootPea = (plantIndex) => {
  const plantElement = plantRefs[plantIndex];
  if (!plantElement || !peaContainerRef.value) return;

  const pea = document.createElement('div');
  pea.className = 'pea';
  peaContainerRef.value.appendChild(pea);

  const startRect = plantElement.getBoundingClientRect();
  const zombieElement = document.querySelector('.zombie-svg');
  if (!zombieElement) return;
  const endRect = zombieElement.getBoundingClientRect();
  const containerRect = peaContainerRef.value.getBoundingClientRect();

  const startX = startRect.left - containerRect.left + startRect.width / 2;
  const startY = startRect.top - containerRect.top + startRect.height / 2;
  
  // 目标是僵尸的头部中心
  const endX = endRect.left - containerRect.left + endRect.width / 2;
  const endY = endRect.top - containerRect.top + endRect.height / 3;

  pea.style.left = `${startX}px`;
  pea.style.top = `${startY}px`;

  requestAnimationFrame(() => {
    pea.style.transform = `translate(${endX - startX}px, ${endY - startY}px) scale(1)`;
  });

  setTimeout(() => { pea.remove(); }, 500);
};

const resetGame = () => {
  gameState.value = 'setup';
  sessionId.value = null;
  questions.value = [];
  currentQuestionIndex.value = 0;
  score.value = 0;
  isSubmitting.value = false;
  isZombieDefeated.value = false;
};

</script>

<style scoped>
/* --- 全局与背景 --- */
@keyframes grass-wave {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}
.pvz-container {
  width: 100%;
  height: calc(100vh - 100px);
  background: linear-gradient(to bottom, #7bdeff 0%, #45a2df 60%, transparent 60%),
              linear-gradient(to bottom, #74c767, #59bd59 60%, #3c9b3a 100%);
  background-size: 100% 100%, 100% 100%;
  display: flex; justify-content: center; align-items: center;
  overflow: hidden; border-radius: 12px; position: relative;
}
.playing-field::before {
    content: ''; position: absolute; bottom: 0; left: 0;
    width: 200%; height: 40%;
    background-image: repeating-linear-gradient( to right,
        rgba(0,0,0,0.1) 0, rgba(0,0,0,0.1) 5%,
        transparent 5%, transparent 10% );
    animation: grass-wave 20s linear infinite;
    z-index: 0;
}
.setup-card, .results-card { width: 500px; text-align: center; background-color: rgba(255, 255, 255, 0.9) !important; backdrop-filter: blur(5px); }
.playing-field { width: 100%; height: 100%; display: flex; flex-direction: column; position: relative; z-index: 1; }
.start-challenge-btn { background-color: #f2a700 !important; color: white !important; border: none !important; font-weight: bold; }

/* --- HUD --- */
.game-hud {
  padding: 5px 20px;
  display: flex;
  justify-content: space-between;
  background-image: url('');
  background-size: auto 100%;
  border-bottom: 3px solid #6f4615;
}
.hud-item { color: #f2a700; font-family: 'Verdana', sans-serif; font-weight: bold; text-shadow: 1px 1px 2px #000; font-size: 20px; }

/* --- 僵尸 --- */
.zombie-area { flex-grow: 1; display: flex; justify-content: flex-end; align-items: flex-end; position: relative; padding-right: 150px; }
.zombie-svg { width: 120px; transition: transform 0.2s ease-in-out; }
.zombie.hit .zombie-svg { animation: zombie-hit 0.3s ease; }
@keyframes zombie-hit { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-10px); } 75% { transform: translateX(10px); } }
.question-bubble { position: absolute; bottom: 90%; left: 50%; transform: translateX(-50%); width: 280px; background-color: rgba(255,255,255,0.9); padding: 15px; border-radius: 15px; box-shadow: 0 4px 12px rgba(0,0,0,0.2); border: 3px solid #666; text-align: center; }
.question-bubble::after { content: ''; position: absolute; bottom: -18px; left: 50%; transform: translateX(-50%); border-width: 20px 20px 0; border-style: solid; border-color: #fff transparent; }
.question-text { font-size: 16px; font-weight: bold; color: #333; }
.zombie-transition-enter-active { transition: all 1s ease-out; animation: zombie-hop-in 1s; }
.zombie-transition-leave-active { transition: all 0.8s ease-in; }
.zombie-transition-enter-from { transform: translateX(200px); opacity: 0; }
.zombie-transition-leave-to { transform: translateY(100px) rotate(-90deg) scale(0.8); opacity: 0; }
@keyframes zombie-hop-in { 0% { transform: translateX(200px); opacity: 0;} 60% { transform: translateX(-20px) translateY(-30px);} 80% { transform: translateX(10px) translateY(0);} 100% { transform: translateX(0) translateY(0); opacity: 1;} }


/* --- 植物 --- */
.plant-area { height: 200px; display: flex; justify-content: space-evenly; align-items: flex-end; padding-bottom: 20px; }
.plant-card { width: 220px; height: 80px; background-color: rgba(0, 0, 0, 0.2); border-radius: 10px; cursor: pointer; display: flex; align-items: center; padding: 10px; transition: all 0.2s ease; border: 2px solid transparent; position: relative; z-index: 2; }
.plant-card.is-disabled { cursor: not-allowed; opacity: 0.7; }
.plant-card:not(.is-disabled):hover { background-color: rgba(0, 0, 0, 0.4); border-color: #fff; }
.plant-card.is-correct { border-color: #67c23a; background-color: rgba(103, 194, 58, 0.4); }
.plant-card.is-incorrect { border-color: #f56c6c; background-color: rgba(245, 108, 108, 0.4); animation: shake 0.5s; }
@keyframes shake { 0%, 100% { transform: translateX(0); } 10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); } 20%, 40%, 60%, 80% { transform: translateX(5px); } }
.plant-svg { width: 80px; height: 80px; flex-shrink: 0; transition: transform 0.2s; }
.plant-card:hover .plant-svg { transform: scale(1.1); }
.option-text { flex-grow: 1; font-weight: bold; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.7); font-size: 16px; padding-left: 5px; }

/* --- 豌豆动画 --- */
.pea-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; overflow: hidden; z-index: 5; }
.pea {
    width: 25px; height: 25px;
    background: radial-gradient(circle at 7px 7px, #dfffdf, #98fb98, #3cb371);
    border: 2px solid #2e8b57;
    border-radius: 50%;
    position: absolute;
    transform: scale(0);
    transition: transform 0.4s cubic-bezier(0.5, 0, 1, 1);
    box-shadow: 0 0 5px #fff;
}
</style>